import mongoose from 'mongoose'
import Model from './model'
const userSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true,
    require: true
  },
  password: {
    type: String,
    require: true
  },
  email: {
    type: String,
    require: true
  }
})

class UserModel extends Model {
  constructor(connection, schema, name) {
    super(connection, schema, name)
  }
  
  // 查询
  findOne(username) {
    return new Promise(async (resolve, reject) => {
      this.model.findOne({
        username
      }, (err, record) => {
        if (err) {
          reject(false)
        } else {
          resolve(record)
        }
      })
    })
  }
  // 插入或更新
  insertOrUpdate(data) {
    return new Promise((resolve, reject) => {
      this.model.findOne({
        username: data.username
      }, (err, record) => {
        if (err) {
          reject(false)
        } else {
          // 不存在
          if (record) {
            // 创建
            let user = new this.model(data)
            user.save((err) => {
              if (err) {
                reject(false)
              } else {
                resolve(data)
              }
            })
          } else {
            // 更新
            this.model.findOneAndUpdate({
              username: data.username
            }, data, {
              new: true,
              upsert: true
            }, (err, res) => {
              if (err) {
                reject(false)
              } else {
                resolve(res)
              }
            })
          }
        }
      })
    })
  }
  // 创建
  create(data) {
    return new Promise((resolve, reject) => {
      let user = new this.model(data)
      user.save((err) => {
        if (err) {
          reject(false)
        } else {
          resolve(data)
        }
      })
    })
  }
}

const user = new UserModel(mongoose, userSchema, 'user')
export default user
